const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const OpenBrowserPlugin = require('open-browser-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;//打包文件分析工具
const TerserPlugin = require('terser-webpack-plugin');//代码压缩工具
//webpack-dashboard直观显示webpack构建
const DashboardPlugin = require('webpack-dashboard/plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const path = require("path")     //引入node的path模块
var ENV = process.env.NODE_ENV;
console.log("process.env.NODE_ENV: ",process.env.NODE_ENV);
var isProd = ENV === 'production';
/**
 * OS Platform
 * Decide browser name for open browser automatic
 */
var isWin = /^win/.test(process.platform);
var isOSX = /^darwin/.test(process.platform);
var browserName = isWin ? 'chrome' : isOSX ? 'google chrome' : 'google-chrome';
var devPlugins = [
    new BundleAnalyzerPlugin({
        analyzerMode: 'static',
        openAnalyzer: false
    })
];
console.log("path.resolve__dirname, /www/ ", __dirname + "/www/")
module.exports = {
    devtool: 'eval-source-map',
    mode:ENV,//development
    entry: {
        pc:__dirname + "/src/main.ts",
        // vendor: ['vue', 'axios']
    },//已多次提及的唯一入口文件
    output: {
        path: __dirname + "/www",//打包后的文件存放的地方
        publicPath: '/www', // 通过devServer访问路径
        filename:  'scripts/[name].bundle.js'//打包后输出文件的文件名
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: __dirname + 'node_modules',
                include: __dirname + 'src',
                options: {
                    presets: ['env']
                },
            },
            //loader的顺序 默认是从右向左执行
            //多个loader 需要[]
            {
                test: /\.vue$/,
                loader: 'vue-loader',
            },
            {
                test: /\.css$/,
                use: [
                    // 'vue-style-loader',
                    MiniCssExtractPlugin.loader,
                    // 'cache-loader',
                    'css-loader?sourceMap',
                    'postcss-loader',//给css 前缀
                ],
            },
            {
                test: /\.scss$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    // 'cache-loader',
                    // 'vue-style-loader',
                    'css-loader',
                    'postcss-loader',
                    'sass-loader'
                ],
            },
            {
                test: /\.sass$/,
                use: [
                    'vue-style-loader',
                    'css-loader',
                    'postcss-loader',
                    'sass-loader?indentedSyntax'
                ],
            },
            // {
            //     test: /\.ts$/,
            //     exclude: /node_modules/,
            //     enforce: 'pre',
            //     loader: 'tslint-loader'
            // },
            {
                test: /\.tsx?$/,
                loader: 'ts-loader',
                exclude: /node_modules/,
                options: {
                    appendTsSuffixTo: [/\.vue$/],
                }
            },
            {
                // ASSET LOADER
                // Reference: https://github.com/webpack/url-loader
                // Copy png, jpg, jpeg, gif, svg, woff, woff2, ttf, eot files to output
                // Rename the file using the asset hash
                // Pass along the updated reference to your code
                // You can add here any file extension you want to get copied to your output

                test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|eot|otf|ttf)$/,
                use: [
                    // 'cache-loader',
                    {
                        loader: 'url-loader',
                        options: {
                            limit: 8192,
                            name: '[path][name].[hash].[ext]'
                        }
                    }
                ]
            },
        ]
    },
    devServer: {
        contentBase: __dirname + "/www/",//本地服务器所加载的页面所在的目录
        port: 8384,
        host: "localhost",
        hot: true,
        // historyApiFallback: true,//不跳转
        // inline: true//实时刷新
    },
    resolve: {
        extensions: ['.js', '.vue', '.json', '.ts'],
        alias: {
            // '@': resolve('src'),
            'vue$': 'vue/dist/vue.esm.js'
        }
    },
    plugins: [
        new webpack.BannerPlugin('版权所有，翻版必究'),
        new VueLoaderPlugin(),
        new HtmlWebpackPlugin({
            template: __dirname + "/src/index.html",//new 一个这个插件的实例，并传入相关的参数
            filename:"index.html",//copy后的名字
            minify:{
                // collapseWhitespace: true,//html  一行
                hash:true,//hash 值
            }
        }),
        new webpack.HotModuleReplacementPlugin(),
        new OpenBrowserPlugin({
            url: 'http://localhost:8384/www/',
            browser: browserName
        }),
        new DashboardPlugin(),
        // new BundleAnalyzerPlugin({
        //     analyzerMode: 'static',
        //     openAnalyzer: false
        // }),
        new MiniCssExtractPlugin({//样式抽取
            filename: isProd ? "css/[name].[hash].bundle.css" : "css/[name].bundle.css"
        }),
    ],
    //自动化分离
    optimization: {
        minimizer: [
            new TerserPlugin({//代码压缩工具
                cache: true,
                parallel: true,
                sourceMap: isProd ? true : false,
                exclude: /\.min\.js$/gi,
            }),
        ],
        splitChunks: {
            chunks: 'all',
            cacheGroups: {
                vendor: {
                    test: /[\\/]node_modules[\\/]/,//表示要过滤 modules，默认为所有的 modules
                    reuseExistingChunk: true,//表示是否使用已有的 chunk，如果为 true 则表示如果当前的 chunk 包含的模块已经被抽取出去了，那么将不会重新生成新的。
                    priority: -10,//表示抽取权重，数字越大表示优先级越高
                    chunks: 'initial',
                    minChunks: 2,
                }
            }
        }
    },
}